package org.openspml.providers.one_c.commands;

import java.util.List;

import org.openspml.message.Modification;
import org.openspml.message.ModifyRequest;
import org.openspml.message.SpmlResponse;
import org.openspml.providers.one_c.api.connection.GlobalContext;
import org.openspml.providers.one_c.api.users.InfoBaseUser;
import org.openspml.providers.one_c.api.users.InfoBaseUsersManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Modify user.
 * 
 * @author <A href="mailto:abashev at gmail dot com">Alexey Abashev</A>
 * @version $Id$
 */
public class ModifyRequestCommand {
	private final Logger log = LoggerFactory.getLogger(ModifyRequestCommand.class);

	public SpmlResponse execute(GlobalContext context, ModifyRequest request) {
		SpmlResponse response = request.createResponse();

		final String id = request.getIdentifierString();

		try {
			InfoBaseUsersManager manager = context.getInfoBaseUsers();
			InfoBaseUser user = manager.findByName(id);
			
			if (user != null) {
				log.trace("Modify user with id [{}]", id);

				@SuppressWarnings("unchecked")
				List<Modification> modifications = request.getModifications();
				
				for (Modification mod : modifications) {
					String name = mod.getName();
					Object value = mod.getValue();
					
					if (name.equals(AddRequestCommand.FIRST_NAME)) {
						String fullName = user.getFullName();
						String newFullName = value + " " + fullName.substring(fullName.indexOf(' ') + 1);
						
						log.trace("Changing full name from [{}] to [{}] for user [{}]", new Object[] {fullName, newFullName, id});

						user.setFullName(newFullName);
						user.write();
					} else if (name.equals(AddRequestCommand.LAST_NAME)) {
						String fullName = user.getFullName();
						String newFullName = fullName.substring(0, fullName.indexOf(' ')) + " " + value;

						log.trace("Changing full name from [{}] to [{}] for user [{}]", new Object[] {fullName, newFullName, id});

						user.setFullName(newFullName);
						user.write();
					} else if (name.equals(AddRequestCommand.PASSWORD)) {
						log.trace("Changing password for for user [{}]", name);

						user.setPassword((String) mod.getValue());
						user.write();
					} else {
						log.info("Unsupported modification [name={};value={}]", name, mod.getValue());
					}
				}
				
				response.setResult(SpmlResponse.RESULT_SUCCESS);
			} else {
				log.warn("User with id [{}] not found", id);
				
				response.setResult(SpmlResponse.RESULT_FAILURE);
				response.setError(SpmlResponse.ERROR_NO_SUCH_IDENTIFIER);
			}
		} catch (Exception e) {
			log.error("Unable to create user [" + id + "]", e);
			
	        response.setError(SpmlResponse.ERROR_CUSTOM_ERROR);
	        response.setErrorMessage(e);
		}
		
		return response;
	}
}
